#include <thread>
#include "../../common/message.hpp"
#include "../../common/net.hpp"
#include "../../common/dispatcher.hpp"
#include "../../common/detail.hpp"

void onRpcResponse(const rpc::BaseConnection::ptr &conn, rpc::RpcResponse::ptr &msg)
{
    LOG(INFO,"收到Rpc响应");
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}
void onTopicRespnse(const rpc::BaseConnection::ptr &conn, rpc::TopicResponse::ptr &msg)
{
    LOG(INFO,"收到topic响应");
    std::string body = msg->serialize();
    std::cout << body << std::endl;
}

int main()
{
    std::shared_ptr<rpc::Dispatcher> dispatcher = std::make_shared< rpc::Dispatcher>();//创建一个dispatcher
    dispatcher->registerHandler<rpc::RpcResponse>(rpc::MType::RSP_RPC,onRpcResponse);//把onRpcResponse进行注册到dispatcher
    dispatcher->registerHandler<rpc::TopicResponse>(rpc::MType::RSP_TOPIC,onTopicRespnse);
    rpc::BaseClient::ptr client = rpc::ClientFactory::create("127.0.0.1", 9090);
    rpc::MessageCallback message_cb = std::bind(&rpc::Dispatcher::onMessage,dispatcher.get(),std::placeholders::_1,std::placeholders::_2);
    client->setMessageCallback(message_cb);//将dispatcher里面的onMessage方法注册给客户端->onMessage根据类型来进行调用不同的回调
    client->connect();
    rpc::RpcRequest::ptr rpc_req = rpc::MessageFactory::create<rpc::RpcRequest>();
    rpc_req->setId("11111");
    rpc_req->setMType(rpc::MType::REQ_RPC);
    rpc_req->setMethod("Add");
    Json::Value param;
    param["num1"] = 11;
    param["num2"] = 22;
    rpc_req->setParams(param);
    client->send(rpc_req);
    auto topic_req = rpc::MessageFactory::create<rpc::TopicRequest>();
    topic_req->setId("22222");
    topic_req->setMType(rpc::MType::REQ_TOPIC);
    topic_req->setOptype(rpc::TopicOptype::TOPIC_CREATE);
    topic_req->setTopicKey("news");
    client->send(topic_req);
    std::this_thread::sleep_for(std::chrono::seconds(10));
    client->shutdown();
    return 0;
}